package com.hackathon.chgk.data;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.hackathon.chgk.data.dao.Task;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	private static final String DATABASE_NAME = "4gk_tasks.db";
	private static final int DATABASE_VERSION = 1;

	private Dao<Task, Integer> taskDao;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}
	
	@Override
	public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
		try {
			TableUtils.createTable(connectionSource, Task.class);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {
		try {
			TableUtils.dropTable(connectionSource, Task.class, true);
			onCreate(sqliteDatabase, connectionSource);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + oldVer + " to new "
					+ newVer, e);
		}
	}

	public Dao<Task, Integer> getTaskDao() throws SQLException {
		if (taskDao == null) {
			taskDao = getDao(Task.class);
		}
		return taskDao;
	}
	
	public void createTask(Task task) {
		
		try {
			
			Dao<Task, Integer> dao = getTaskDao();			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put(Task.HASHCODE_FIELD_NAME, task.getHashCode());
			
			if (dao.queryForFieldValues(map).size() == 0) {
				dao.create(task);
			}			
		} 
		catch (SQLException e) {
			throw new RuntimeException(e);
		}		
	}
	
	public void createTasks(List<Task> tasks) {
		
		for(Task task : tasks) {			
			createTask(task);
		}
		
		try {
			List<Task> tasks1 = getTaskDao().queryForAll();
			for(Task t : tasks1) {
				Log.d("db_content", t.getHashCode()+": "+ t.getText());
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
